package com.mall.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mall.untils.Constants;
import com.mall.untils.HttpClientUtil;
import com.mall.untils.MapUtil;
import com.mall.untils.ResponseJsonUtil;
import com.mall.untils.StringUtil;
import com.mall.untils.TicketUtil;
import com.mall.untils.UploadImgOrRecorderUtil;

@Service
public class UserService {

	
	private Logger logger = LoggerFactory.getLogger(UserService.class);
	@Resource JdbcTemplate jdbcTemplate;
	@Resource TicketUtil ticketUtil;
	
	public void unsubscribe(Map<String, Object> userMap) {
		String openid = MapUtils.getString(userMap, "openid");
		String sql="update t_e_wx_user set subscribe=0 where open_id=?";
		try {
			jdbcTemplate.update(sql,openid);
		} catch (Exception e) {
			logger.info("取消关注信息更新失败！");
		}
	}

	public void add_user(Map<String, Object> userMap) {
		
		int subscribe = MapUtils.getIntValue(userMap, "subscribe");
        String openId = MapUtils.getString(userMap, "openid");
        String nickName = MapUtils.getString(userMap, "nickname");
        int sex = MapUtils.getIntValue(userMap, "sex");
        String city = MapUtils.getString(userMap, "city");
        String province = MapUtils.getString(userMap, "province");
        String head_imgurl = MapUtils.getString(userMap, "head_imgurl");
        long subscribe_time = MapUtils.getLongValue(userMap, "subscribe_time");
        
    	Map<String, Object> queryForMap = jdbcTemplate.queryForMap("SELECT FROM_UNIXTIME("+subscribe_time+") timeInfo");
    	
    	if(!StringUtils.isEmpty(openId) && null!=openId){
    		String sql="";
    		Map<String, Object> userInfo = getWXUserOpenId(openId);
    		logger.info("用户的相关信息================="+userMap);
    		logger.info("最后关注的时间是：====================>" + queryForMap.get("timeInfo"));	
    		if (userInfo != null && userInfo.size()>0) {
    			sql = "update t_e_wx_user set nick_name = ?, sex = ?, province = ?, " +
    					"city = ?, head_img_url = ?, subscribe = ?, subscribe_time = ? where open_id = ?";
    		} else {//新用户
    			sql = "insert into t_e_wx_user (nick_name, sex, province, city, head_img_url, subscribe, subscribe_time, open_id, create_at) values (?, ?, ?, ?, ?, ?, ?, ?, now())";
    		}
    		logger.info("---nickName======= nickName:"+nickName+"======编码之后:"+StringUtil.getByteToString(nickName)+"=========="+StringUtils.isEmpty(StringUtil.getByteToString(nickName)));
    		if(StringUtils.isEmpty(nickName)){
    			nickName="无";
    		}
    		try {
    			jdbcTemplate.update(sql, nickName, sex, province, city, head_imgurl, subscribe, queryForMap.get("timeInfo"), openId);
    		} catch (Exception e) {
    			e.printStackTrace();
    			
    			//=========================
    			if(!StringUtils.isEmpty(openId) && null!=openId){
    				userInfo = getWXUserOpenId(openId);
    	    		logger.info("用户的相关信息================="+userMap);
    	    		logger.info("最后关注的时间是：====================>" + queryForMap.get("timeInfo"));	
    	    		if (userInfo != null && userInfo.size()>0) {
    	    			sql = "update t_e_wx_user set nick_name = ?, sex = ?, province = ?, " +
    	    					"city = ?, head_img_url = ?, subscribe = ?, subscribe_time = ? where open_id = ?";
    	    		} else {//新用户
    	    			sql = "insert into t_e_wx_user (nick_name, sex, province, city, head_img_url, subscribe, subscribe_time, open_id, create_at) values (?, ?, ?, ?, ?, ?, ?, ?, now())";
    	    		}
    	    		logger.info("---nickName======= nickName:"+nickName+"======编码之后:"+StringUtil.getByteToString(nickName)+"=========="+StringUtils.isEmpty(StringUtil.getByteToString(nickName)));
    	    		if(StringUtils.isEmpty(nickName)){
    	    			nickName="无";
    	    		}	
    	    		jdbcTemplate.update(sql, "无", sex, province, city, head_imgurl, subscribe, queryForMap.get("timeInfo"), openId);
    			}
    			//=========================
    			
    			logger.info("微信关注并添加新用户出错！");
    		}
    	}
    	
	}
	/**
     * 获取open_id是否存在
     *
     * @param openId
     * @return
     */
    public Map<String, Object> getWXUserOpenId(String openId) {
        List<Map<String, Object>> queryList = null;
        String sql = "SELECT * FROM t_e_wx_user WHERE open_id = ? limit 1";
        queryList = jdbcTemplate.queryForList(sql, openId);
        if (queryList != null && queryList.size() > 0) {
        	return  queryList.get(0);
        } else {
        	return null;
        }
    }

	public String send_id_code(Map<String, Object> paraMap) {
        final String phoneNum = MapUtil.getStringValue(paraMap, "phone");

        final String idCode = this.getCode();

        if (idCode.equals("-1")) {
            return ResponseJsonUtil.responseDefineFailed("");
        } else {
//            new SMSUtil().sendCode(phoneNum, idCode);
            logger.info("send_id_code==========>phone_num:" + phoneNum + ",idCode:" + idCode);
            return ResponseJsonUtil.responseSuccess(idCode);
        }
    }
		 /**
	     * 验证码规则生成
	     */
	    private String getCode() {
	        long temp;
	        temp = Math.round(Math.random() * 8999 + 1000);
	        return temp + "";
	    }

		public int web_save_register(Map<String, Object> paraMap) {
			String phone = MapUtil.getStringValue(paraMap, "phone");
			String open_id = MapUtil.getStringValue(paraMap, "open_id");
			String idenID = MapUtil.getStringValue(paraMap, "idenID");
			String identity = MapUtil.getStringValue(paraMap, "identity");
			String sql="update t_e_wx_user set user_type=? , user_id=? , phone=? where open_id=?";
			try {
				int update = jdbcTemplate.update(sql,identity,idenID,phone,open_id);
				return update;
			} catch (Exception e) {
				logger.info("注册信息有问题！");
				return 0;
			}
		}
		
		public int web_update_user_head_img(Map<String, Object> paraMap) {
			String goods_reason_img = MapUtil.getStringValue(paraMap, "goods_reason_img");
		    String open_id = MapUtil.getStringValue(paraMap, "open_id");
			logger.info("园所更新图片=====open_id=="+open_id+"===="+goods_reason_img);
			String url = String.format(Constants.DOWNLOAD_MEDIA_URL, ticketUtil.getAccess_token(), goods_reason_img);
            String returnUrl = null;
			try {
				returnUrl = UploadImgOrRecorderUtil.saveFilesByName(url, Constants.getImgName());
			} catch (Exception e) {
				e.printStackTrace();
			}
            goods_reason_img= returnUrl;
            List<NameValuePair> params=new ArrayList<NameValuePair>();
            String sql="select user_id from t_e_wx_user where  open_id=?";
            int user_id = jdbcTemplate.queryForInt(sql,open_id);
            params.add(new BasicNameValuePair("userid",String.valueOf(user_id)));
            params.add(new BasicNameValuePair("url",goods_reason_img));
        	String string = HttpClientUtil.get(Constants.php_url+"insert_img_api.php", params);

        	return 1;
		}


		public Map<String, Object> web_find_user(int type_flag_id) {
			try {
				String sql="select * from t_e_wx_user where user_id=?";
				Map<String, Object> queryForMap = jdbcTemplate.queryForMap(sql,type_flag_id);
				return queryForMap;
			} catch (Exception e) {
				return null;
			}
		}

		public List<Map<String, Object>> get_all_data(Map<String, Object> paraMap, int i) {
			String open_id = MapUtil.getStringValue(paraMap, "open_id");
			List<Map<String, Object>> queryForList =null;
			if(i==1){
				String sql="select * from t_e_individualization where id in(select new_id from t_e_user_history where open_id=? and type=1)";
				queryForList = jdbcTemplate.queryForList(sql,open_id);
				List<Map<String, Object>> queryForList2 = jdbcTemplate.queryForList("select new_id,date_format(create_time,'%Y-%m-%d') create_time from t_e_user_history where open_id=?",open_id);
				for (Map<String, Object> map : queryForList) {
					for (Map<String, Object> map2 : queryForList2) {
						if(map.get("id").equals(map2.get("new_id"))){
							map.put("look_time", map2.get("create_time"));
							break;
						}
					}
				}
			}else{
				String sql="select new_id from t_e_user_history where open_id=? and type=2";
				queryForList = jdbcTemplate.queryForList(sql,open_id);
			}
			return queryForList;
		}


}
